package controllers;

import java.io.IOException;
import java.io.Serializable;
import java.sql.Time;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.AjaxBehaviorEvent;

import testerbeans.EmailBean;
import dao.CandidateDAORemote;
import dao.InterviewDAORemote;
import dao.RoomDAORemote;
import dao.TemplateCategoryDAORemote;
import dao.TemplateDAORemote;
import dto.CandidateDTO;
import dto.CandidateViewDto;
import dto.InterviewDTO;
import dto.InterviewViewDto;
import dto.RoomDTO;
import dto.TemplateCategoryDTO;
import dto.TemplateDTO;
import dto.TemplateViewDto;

@ManagedBean(name = "interviewController")
@SessionScoped
public class InterviewController implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	@EJB
	CandidateDAORemote candidateDAO;
	@EJB
	TemplateDAORemote templateDAO;
	@EJB
	TemplateCategoryDAORemote templateCategoryDAO;
	@EJB
	RoomDAORemote roomDAO;
	@EJB
	InterviewDAORemote interviewDAO;
	@ManagedProperty(value = "#{emailBean}")
	private EmailBean emailBean;

	// templates
	private List<TemplateDTO> templateDTOs;
	private List<TemplateCategoryDTO> templateCategoryDTOs;
	private TemplateDTO selectedTemplate;
	private int selectedTemplateID;
	private String details;
	// rooms
	private List<String> rooms;
	private int selectedRoomID;
	private List<RoomDTO> roomDTOs;
	private RoomDTO selectedRoom;
	private int totalRooms;
	private List<Integer> schedule;
	private List<String> colorList;

	private String errorMessage = "";
	// time and date
	public static final int START_HOUR = 8;
	public static final int END_HOUR = 17;
	public static final int MONDAY = 2;
	public static final int SATURDAY = 7;
	// ids
	private int employeeId;
	// candidate related
	private CandidateViewDto candidate;
	private InterviewViewDto interviewView;

	private List<Integer> hours = new ArrayList<Integer>();
	private List<Integer> minutes = new ArrayList<Integer>();
	private List<Integer> endHours = new ArrayList<Integer>();
	private List<Integer> endMinutes = new ArrayList<Integer>();

	private List<Calendar> week = new ArrayList<Calendar>();
	private List<String> weekDays = new ArrayList<String>();
	private List<String> defaultWeekDays = new ArrayList<String>();
	private List<String> weekDate = new ArrayList<String>();
	private int selectedStartHour;
	private int selectedStartMinute;
	private int selectedEndHour;
	private int selectedEndMinute;
	private Calendar selectedDate;
	private Calendar selectedEndDate;
	private String selDate;
	private InterviewDTO idto;
	private String nextButton;
	private String currentWeek;
	private Boolean reschedule = false;
	private String color;

	private String messageClass;

	/**
	 * Populates the schedule table by taking into account the current room and
	 * the selected week. The table is populated using schedule
	 * ArrayList<Integer>(), which contains the number of occupied places of the
	 * respective room, for the hour interval 08-17, from Monday to Saturday. A
	 * color-coded graphical hint about the ratio between the occupied places
	 * and the total stations is given.
	 * 
	 * @param e
	 * @see #bookRooms()
	 */
	public void getNumberOfStations(AjaxBehaviorEvent e) {
		totalRooms = roomDAO.getRoomByAddress(selectedRoom.getAddress()).getNumberOfStations();
		selectedRoom = roomDAO.getRoomById(selectedRoomID);
		colorList.clear();
		schedule.clear();
		bookRooms();
	}

	/**
	 * Performs an insertion of a new interview in the database. Creates an
	 * object of type InterviewViewDto, in order to be used further, for email
	 * sending. Contains validations for the cases in which the respective room
	 * is full at the desired time, the time interval reserved for the interview
	 * is smaller than the duration, or when the start time of interview has
	 * already passed.
	 * 
	 * @param e
	 * @see #reserve()
	 * @throws Exception
	 */
	@SuppressWarnings("deprecation")
	public void saveInterview(AjaxBehaviorEvent e) throws Exception {
		setIdto(new InterviewDTO());
		getIdto().setAccepted((byte) -1);
		System.out.println("startHour " + selectedStartHour);
		Time tstart = new Time(selectedStartHour, selectedStartMinute, 0);
		Time tend = new Time(selectedEndHour, selectedEndMinute, 0);
		getIdto().setStartTime(tstart);
		getIdto().setEndTime(tend);
		getIdto().setDate(
				new Date(selectedDate.get(Calendar.YEAR) - 1900, selectedDate.get(Calendar.MONTH), selectedDate
						.get(Calendar.DATE)));
		System.out.println("ora curenta " + Calendar.getInstance().get(Calendar.HOUR_OF_DAY));
		if (reserve()) {
			if (((selectedEndHour - selectedStartHour) * 60 + selectedEndMinute - selectedStartMinute) > selectedTemplate
					.getDuration()) {
				if (!((Calendar.getInstance().get(Calendar.DATE) == selectedDate.get(Calendar.DATE)) && ((Calendar
						.getInstance().get(Calendar.HOUR_OF_DAY) + 1 == selectedStartHour && Calendar.getInstance()
						.get(Calendar.MINUTE) >= selectedStartMinute) || Calendar.getInstance().get(
						Calendar.HOUR_OF_DAY) + 1 > selectedStartHour))

				) {
					int id = interviewDAO.addInterview(idto, employeeId, candidate.getId(), selectedTemplateID,
							selectedRoomID);
					InterviewViewDto interview = new InterviewViewDto();
					interview.setId(id);
					TemplateViewDto template = new TemplateViewDto();
					template.setId(selectedTemplateID);
					template.setTitle(selectedTemplate.getTitle());
					interview.setTemplate(template);
					interview.setStartTime(selectedStartHour + ":" + selectedStartMinute + "");
					interview.setEndTime(selectedEndHour + ":" + selectedEndMinute + "");
					interview.setCandidate(candidateDAO.getCandidateByID(candidate.getId()));
					interview.setRoom(selectedRoom);
					interview.setAccepted("N/A");
					interview.setTaken(false);
					interview.setDelete(false);
					interview.setView(true);
					interview.setSend(false);
					interview.setDate(idto.getDate().toString());
					interview.setEndTime(idto.getEndTime().toString());
					interview.setRoom(selectedRoom);
					interview.setStartTime(idto.getStartTime().toString());
					interview.setCandidate(candidateDAO.getCandidateByID(candidate.getId()));
					interview.setButDel("button");
					interview.setButSend("button");
					List<InterviewViewDto> interviews = candidate.getInterviews();
					interviews.add(interview);
					candidate.setInterviews(interviews);
					// set buttons
					interview.setView(true);
					interview.setDelete(false);
					interview.setButDel("button");
					interview.setButView("buttonDis");
					emailBean.setDelete(false);
					interview.setFromRedirect(true);

					emailBean.setInterviewDto(interview);
					errorMessage = "Interview Succesfully added!";
					messageClass = "success";
					reset();
				} else {
					errorMessage = "The selected hour has already passed!";
					messageClass = "errorMessage";
					reset();
				}
				// }
			} else {
				errorMessage = "The duration for taking the selected interview type is higher than the duration allocated for the meeting";
				messageClass = "errorMessage";
				reset();
			}
		} else {
			errorMessage = "Room full for the selected interval!";
			messageClass = "errorMessage";
			reset();
		}
		totalRooms = roomDAO.getRoomByAddress(selectedRoom.getAddress()).getNumberOfStations();
		selectedRoom = roomDAO.getRoomById(selectedRoomID);
		schedule.clear();
		colorList.clear();
		getDateTime(e);
		bookRooms();
	}

	/**
	 * Sets the selected date and time, in order to be further processed. It is
	 * launched at an AjaxBehaviorEvent, and updates the end hour of the
	 * interview with respect to the selected starting time.
	 * 
	 * @see #reset()
	 * @param e
	 */
	public void getDateTime(AjaxBehaviorEvent e) {
		LinkedList<String> numbers = new LinkedList<String>();
		Pattern p = Pattern.compile("\\d+");
		Matcher m = p.matcher(selDate);
		while (m.find()) {
			numbers.add(m.group());
		}
		selectedDate.set(Calendar.YEAR, Integer.parseInt(numbers.get(2)));
		selectedDate.set(Calendar.MONTH, Integer.parseInt(numbers.get(1)) - 1);
		selectedDate.set(Calendar.DATE, Integer.parseInt(numbers.get(0)));
		selectedDate.set(Calendar.HOUR_OF_DAY, selectedStartHour);
		selectedDate.set(Calendar.MINUTE, selectedStartMinute);
		selectedEndHour = selectedStartHour;
		selectedEndMinute = selectedStartMinute;
		endHours.clear();
		endMinutes.clear();
		for (int i = selectedEndHour; i < END_HOUR; i++) {
			endHours.add(i);
		}
		for (int i = selectedEndMinute; i <= 50; i += 10) {
			endMinutes.add(i);
		}
		selectedEndDate.set(Calendar.YEAR, Integer.parseInt(numbers.get(2)));
		selectedEndDate.set(Calendar.MONTH, Integer.parseInt(numbers.get(1)) - 1);
		selectedEndDate.set(Calendar.DATE, Integer.parseInt(numbers.get(0)));
		selectedEndDate.set(Calendar.HOUR_OF_DAY, selectedEndHour);
		selectedEndDate.set(Calendar.MINUTE, selectedEndMinute);
	}

	/**
	 * Displays the selected template's details.
	 * 
	 * @see #assembleDetails()
	 * @param e
	 * @throws Exception
	 */

	public void restartEndMinutes(AjaxBehaviorEvent e) {
		// System.out.println(selectedEndHour + "end hour");
		selectedEndMinute = 0;
		endMinutes.clear();
		for (int i = 0; i <= 50; i += 10) {
			endMinutes.add(i);
		}
		selectedEndDate.set(Calendar.HOUR_OF_DAY, selectedEndHour);
		selectedEndDate.set(Calendar.MINUTE, selectedEndMinute);
	}

	public void setEndMinutes(AjaxBehaviorEvent e) {
		selectedEndDate.set(Calendar.MINUTE, selectedEndMinute);
	}

	public void displayDetails(AjaxBehaviorEvent e) throws Exception {
		try {
			selectedTemplate = templateDAO.getTemplateDTOById(selectedTemplateID);
			templateCategoryDTOs.clear();
			templateCategoryDTOs = templateCategoryDAO.getTemplateCategoryListByTemplate(selectedTemplate);
			assembleDetails();
		} catch (Exception e1) {
			throw new Exception("Template not found!", e1);
		}

	}

	/**
	 * Resets the starting and ending hours to default values
	 */
	public void reset() {
		selectedEndHour = 8;
		selectedEndMinute = 0;
		selectedStartHour = 8;
		selectedStartMinute = 0;
	}

	/**
	 * Updates the week selection button and schedule, with respect to the
	 * displayed schedule
	 * 
	 * @param e
	 */
	public void changeButtonValue(AjaxBehaviorEvent e) {
		reset();
		Calendar calendar;
		if (nextButton.equals("Next week")) {
			calendar = Calendar.getInstance();
			nextButton = "Previous week";
			currentWeek = "Next Week Schedule\n(";
			calendar.set(Calendar.DAY_OF_WEEK, MONDAY);
			calendar.set(Calendar.DATE, calendar.get(Calendar.DATE) + 7);
			currentWeek = currentWeek + calendar.get(Calendar.DATE) + "/" + (calendar.get(Calendar.MONTH) + 1) + "/"
					+ calendar.get(Calendar.YEAR) + " - ";
			calendar.set(Calendar.DAY_OF_WEEK, SATURDAY);
			currentWeek = currentWeek + calendar.get(Calendar.DATE) + "/" + (calendar.get(Calendar.MONTH) + 1) + "/"
					+ calendar.get(Calendar.YEAR) + ")";
		} else {
			calendar = Calendar.getInstance();
			nextButton = "Next week";
			currentWeek = "Current Week Schedule\n(";
			calendar.set(Calendar.DAY_OF_WEEK, MONDAY);
			currentWeek = currentWeek + calendar.get(Calendar.DATE) + "/" + (calendar.get(Calendar.MONTH) + 1) + "/"
					+ calendar.get(Calendar.YEAR) + " - ";
			calendar.set(Calendar.DAY_OF_WEEK, SATURDAY);
			currentWeek = currentWeek + calendar.get(Calendar.DATE) + "/" + (calendar.get(Calendar.MONTH) + 1) + "/"
					+ calendar.get(Calendar.YEAR) + ")";
		}
		bookRooms();
	}

	/**
	 * Method responsible for setting default data when the page is opened. The
	 * following fields are updated: schedule table, drop-down lists for
	 * templates, rooms, date and hours and selected variables are set on
	 * default.
	 * 
	 * @throws IOException
	 */
	@PostConstruct
	public void initTemplates() throws IOException {
		// templates
		nextButton = "Next week";
		Calendar calendar = Calendar.getInstance();
		currentWeek = "Current Week Schedule\n(";
		calendar.set(Calendar.DAY_OF_WEEK, MONDAY);
		currentWeek = currentWeek + calendar.get(Calendar.DATE) + "/" + (calendar.get(Calendar.MONTH) + 1) + "/"
				+ calendar.get(Calendar.YEAR) + " - ";
		calendar.set(Calendar.DAY_OF_WEEK, SATURDAY);
		currentWeek = currentWeek + calendar.get(Calendar.DATE) + "/" + (calendar.get(Calendar.MONTH) + 1) + "/"
				+ calendar.get(Calendar.YEAR) + ")";
		templateDTOs = templateDAO.findAllTemplates();
		if (templateDTOs == null || templateDTOs.size() == 0) {
			FacesContext.getCurrentInstance().getExternalContext().redirect(
					"/MSGCandidateTesting/faces/createTemplate.xhtml");
		} else {
			selectedTemplate = templateDTOs.get(0);
			selectedTemplateID = selectedTemplate.getId();
			templateCategoryDTOs = new ArrayList<TemplateCategoryDTO>();
			templateCategoryDTOs = templateCategoryDAO.getTemplateCategoryListByTemplate(selectedTemplate);
			assembleDetails();
			// rooms
			roomDTOs = roomDAO.getAllRooms();
			selectedRoom = roomDTOs.get(0);
			selectedRoomID = selectedRoom.getId();
			schedule = new ArrayList<Integer>();
			totalRooms = roomDAO.getRoomByAddress(selectedRoom.getAddress()).getNumberOfStations();
			bookRooms();
			for (int i = START_HOUR; i < END_HOUR; i++) {
				hours.add(i);
				endHours.add(i);
			}
			// endHours.add(END_HOUR+1);
			for (int i = 0; i <= 50; i += 10) {
				minutes.add(i);
				endMinutes.add(i);
			}
			defaultWeekDays.add("Sunday");
			defaultWeekDays.add("Sunday");
			defaultWeekDays.add("Monday");
			defaultWeekDays.add("Tuesday");
			defaultWeekDays.add("Wednesday");
			defaultWeekDays.add("Thursday");
			defaultWeekDays.add("Friday");
			defaultWeekDays.add("Saturday");
			selectedStartHour = START_HOUR;
			selectedStartMinute = minutes.get(0);
			selectedEndHour = selectedStartHour;
			selectedEndMinute = selectedStartMinute;
			for (int i = Calendar.getInstance().get(Calendar.DAY_OF_WEEK); i <= SATURDAY; i++) {
				weekDays.add(defaultWeekDays.get(i));
				selectedDate = Calendar.getInstance();
				selectedDate.set(Calendar.DAY_OF_WEEK, i);
				week.add(selectedDate);
			}
			for (int i = 2; i <= SATURDAY; i++) {
				weekDays.add(defaultWeekDays.get(i));
				selectedDate = Calendar.getInstance();
				selectedDate.set(Calendar.DAY_OF_WEEK, i);
				selectedDate.set(Calendar.WEEK_OF_YEAR, Calendar.getInstance().get(Calendar.WEEK_OF_YEAR) + 1);
				week.add(selectedDate);
			}
			selectedDate = week.get(0);
			selectedEndDate = Calendar.getInstance();
			selectedEndDate = week.get(0);
			String s;
			for (Calendar c : week) {
				s = weekDays.get(week.indexOf(c)) + " - ";
				if (c.get(Calendar.DATE) < 10) {
					s = s + "0";
				}
				s = s + c.get(Calendar.DATE) + "/";
				if (c.get(Calendar.MONTH) < 10) {
					s = s + "0";
				}
				s = s + (c.get(Calendar.MONTH) + 1) + "/" + c.get(Calendar.YEAR);
				weekDate.add(s);
			}
			selDate = weekDate.get(0);
			LinkedList<String> numbers = new LinkedList<String>();
			Pattern p = Pattern.compile("\\d+");
			Matcher m = p.matcher(selDate);
			while (m.find()) {
				numbers.add(m.group());
			}
			selectedDate.set(Calendar.DATE, Integer.parseInt(numbers.get(0)));
			selectedDate.set(Calendar.MONTH, Integer.parseInt(numbers.get(1)) - 1);
			selectedDate.set(Calendar.YEAR, Integer.parseInt(numbers.get(2)));
			selectedDate.set(Calendar.HOUR_OF_DAY, selectedStartHour);
			selectedDate.set(Calendar.MINUTE, selectedStartMinute);
			selectedEndDate.set(Calendar.DATE, Integer.parseInt(numbers.get(0)));
			selectedEndDate.set(Calendar.MONTH, Integer.parseInt(numbers.get(1)) - 1);
			selectedEndDate.set(Calendar.YEAR, Integer.parseInt(numbers.get(2)));
			selectedEndDate.set(Calendar.HOUR_OF_DAY, selectedEndHour);
			selectedEndDate.set(Calendar.MINUTE, selectedEndMinute);
		}
	}

	/**
	 * Populates the schedule and colorList ArrayLists with details which will
	 * be further used by {@link #getNumberOfStations(AjaxBehaviorEvent).}. It
	 * is called whenever the selected room or selected week is changed
	 */
	public void bookRooms() {
		totalRooms = roomDAO.getRoomByAddress(selectedRoom.getAddress()).getNumberOfStations();
		Calendar cal = Calendar.getInstance();
		int j, i;
		schedule = new ArrayList<Integer>();
		colorList = new ArrayList<String>();
		if (!nextButton.equals("Next week"))
			cal.set(Calendar.WEEK_OF_YEAR, cal.get(Calendar.WEEK_OF_YEAR) + 1);
		schedule.clear();
		colorList.clear();
		for (i = MONDAY; i <= SATURDAY; i++) {
			cal.set(Calendar.DAY_OF_WEEK, i);
			for (j = START_HOUR; j <= END_HOUR; j++) {
				cal.set(Calendar.HOUR_OF_DAY, j);
				cal.set(Calendar.MINUTE, 0);
				schedule.add((i - MONDAY) * 9 + (j - START_HOUR), roomDAO.getBusyPlacesInterval2(cal, roomDAO
						.getRoomByAddress(selectedRoom.getAddress()).getId(), cal));
				if ((float) roomDAO.getBusyPlacesInterval2(cal, roomDAO.getRoomByAddress(selectedRoom.getAddress())
						.getId(), cal)
						/ totalRooms < 0.25)
					colorList.add((i - MONDAY) * 9 + (j - START_HOUR), "green");
				else if ((float) roomDAO.getBusyPlacesInterval2(cal, roomDAO
						.getRoomByAddress(selectedRoom.getAddress()).getId(), cal)
						/ totalRooms < 0.5)
					colorList.add((i - MONDAY) * 9 + (j - START_HOUR), "yellow");
				else if ((float) roomDAO.getBusyPlacesInterval2(cal, roomDAO
						.getRoomByAddress(selectedRoom.getAddress()).getId(), cal)
						/ totalRooms < 0.75)
					colorList.add((i - MONDAY) * 9 + (j - START_HOUR), "orange");
				else
					colorList.add((i - MONDAY) * 9 + (j - START_HOUR), "red");
			}
		}
	}

	/**
	 * Verifies if the room is full in the selected interval.
	 * 
	 * @return true if the room contains at least one free station, false
	 *         otherwise.
	 */
	public boolean reserve() {
		int ok = 0;
		Calendar cal = Calendar.getInstance();
		Calendar endCal = Calendar.getInstance();
		LinkedList<String> numbers = new LinkedList<String>();
		Pattern p = Pattern.compile("\\d+");
		Matcher m = p.matcher(selDate);
		while (m.find()) {
			numbers.add(m.group());
		}
		cal.set(Calendar.DATE, Integer.parseInt(numbers.get(0)));
		cal.set(Calendar.MONTH, Integer.parseInt(numbers.get(1)) - 1);
		cal.set(Calendar.YEAR, Integer.parseInt(numbers.get(2)));
		cal.set(Calendar.HOUR_OF_DAY, selectedStartHour);
		cal.set(Calendar.MINUTE, selectedStartMinute);

		endCal.set(Calendar.DATE, Integer.parseInt(numbers.get(0)));
		endCal.set(Calendar.MONTH, Integer.parseInt(numbers.get(1)) - 1);
		endCal.set(Calendar.YEAR, Integer.parseInt(numbers.get(2)));
		endCal.set(Calendar.HOUR_OF_DAY, selectedEndHour);
		endCal.set(Calendar.MINUTE, selectedEndMinute);

		// System.out.println("busyyy");
		// System.out.println(roomDAO.getBusyPlacesInterval(cal, roomDAO
		// .getRoomByAddress(selectedRoom.getAddress()).getId(), endCal));
		// System.out.println("busy ");
		System.out.println("end " + selectedEndHour);
		if (selectedStartHour < selectedEndHour) {
			for (int i = selectedStartHour; i < selectedEndHour; i++) {
				cal.set(Calendar.HOUR_OF_DAY, i);
				endCal.set(Calendar.HOUR_OF_DAY, i + 1);
				System.out.println("CAL " + cal.get(Calendar.HOUR_OF_DAY) + ":" + cal.get(Calendar.MINUTE));
				System.out.println("ENDCAL " + endCal.get(Calendar.HOUR_OF_DAY) + ":" + endCal.get(Calendar.MINUTE));
				if (!((roomDAO.getBusyPlacesInterval(cal, roomDAO.getRoomByAddress(selectedRoom.getAddress()).getId(),
						endCal)) < totalRooms)) {
					ok = 1;
				}
			}
		} else {
			if (!((roomDAO.getBusyPlacesInterval(cal, roomDAO.getRoomByAddress(selectedRoom.getAddress()).getId(),
					endCal)) < totalRooms)) {
				ok = 1;
			}
		}
		if (ok == 1)
			return false;
		return true;
	}

	/**
	 * Builds the string containing details about a chosen template: id, title,
	 * duration and number of questions per category.
	 */
	public void assembleDetails() {
		details = "Details: \n";
		details = details + "	Template Id: " + selectedTemplate.getId() + "\n";
		details = details + "	Title: " + selectedTemplate.getTitle() + "\n";
		details = details + "	Duration: " + selectedTemplate.getDuration() + "\n";
		details = details + "\nQuestions per categories: \n";
		templateCategoryDTOs.clear();
		templateCategoryDTOs = templateCategoryDAO.getTemplateCategoryListByTemplate(selectedTemplate);
		for (TemplateCategoryDTO tcDTO : templateCategoryDTOs) {
			details = details + "	Category: " + tcDTO.getCategory().getName() + "\n	No. of questions: "
					+ tcDTO.getNumberOfQuestions() + "\n\n";
		}
	}

	@SuppressWarnings("deprecation")
	public void newSchedule() throws Exception {
		Time tstart = new Time(selectedStartHour, selectedStartMinute, 0);
		Time tend = new Time(selectedEndHour, selectedEndMinute, 0);
		getIdto().setStartTime(tstart);
		getIdto().setEndTime(tend);
		getIdto().setAccepted((byte) -1);

		getIdto().setDate(
				new Date(selectedDate.get(Calendar.YEAR) - 1900, selectedDate.get(Calendar.MONTH), selectedDate
						.get(Calendar.DATE)));

		System.out.println("date " + getIdto().getDate().toString());
		if (reserve()) {
			if (((selectedEndHour - selectedStartHour) * 60 + selectedEndMinute - selectedStartMinute) > selectedTemplate
					.getDuration()) {
				if (!(Calendar.getInstance().get(Calendar.DATE) == selectedDate.get(Calendar.DATE) && Calendar
						.getInstance().get(Calendar.HOUR_OF_DAY) >= selectedDate.get(Calendar.HOUR_OF_DAY))) 
				
				{
					int id = idto.getId();
					interviewDAO.addInterview(idto, employeeId, candidate.getId(), selectedTemplateID, selectedRoomID);
					// System.out.println(idto.getId() + " vs " + id);
					List<InterviewViewDto> interv = candidate.getInterviews();
					// System.out.println("Size of interviews of ic is "+interv.size());
					for (InterviewViewDto interview : interv)
						if (interview.getId() == id) {
							TemplateViewDto template = new TemplateViewDto();
							template.setId(selectedTemplateID);
							template.setTitle(selectedTemplate.getTitle());
							interview.setTemplate(template);
							interview.setStartTime(selectedStartHour + ":" + selectedStartMinute + "");
							interview.setEndTime(selectedEndHour + ":" + selectedEndMinute + "");
							interview.setCandidate(candidateDAO.getCandidateByID(candidate.getId()));
							interview.setRoom(selectedRoom);
							interview.setAccepted("N/A");
							interview.setTaken(false);
							interview.setDelete(true);
							interview.setView(true);
							interview.setSend(false);
							interview.setFromRedirect(true);
							interview.setDate(idto.getDate().toString());
							interview.setEndTime(idto.getEndTime().toString());
							interview.setRoom(selectedRoom);
							interview.setStartTime(idto.getStartTime().toString());
							interview.setCandidate(candidateDAO.getCandidateByID(candidate.getId()));
							interview.setButDel("buttonDis");
							interview.setButSend("button");
							interview.setButView("buttonDis");
							interview.setFromRedirect(true);
							setInterviewView(interview);
							emailBean.setInterviewDto(interview);
							System.out.println("Set fromredirect in emilbean " + emailBean.getFromRedirect());
						}
					candidate.setInterviews(interv);
					errorMessage = "Interview Succesfully edited!";
					messageClass = "success";
					reset();
				} else {
					errorMessage = "The selected hour has already passed!";
					messageClass = "errorMessage";
					reset();
				}
			} else {
				System.out.println("the interval is"
						+ ((selectedEndHour - selectedStartHour) * 60 + selectedEndMinute - selectedStartMinute));
				errorMessage = "The duration for taking the selected interview type is higher than the duration allocated for the meeting";
				messageClass = "errorMessage";
				reset();
			}
		} else {

			errorMessage = "Room full for the selected interval!";
			messageClass = "errorMessage";
			reset();
		}
		totalRooms = roomDAO.getRoomByAddress(selectedRoom.getAddress()).getNumberOfStations();
		selectedRoom = roomDAO.getRoomById(selectedRoomID);
		schedule.clear();
		bookRooms();

		InterviewDTO test = interviewDAO.getInterview(idto.getId());
		System.out.println("Retreived interview with id: " + test.getId() + " at date " + test.getDate()
				+ " starttime: " + test.getStartTime().toString() + "" + " endtime " + test.getEndTime() + " in room "
				+ test.getRoom().getAddress() + " ");

		// initialize variablies for redirecting to send email page

		String link = (String) candidateDAO.getLink(test.getCandidate().getId());

		getEmailBean().setLink(link);

		int duration = computeDuration(test);
		emailBean.setDuration(duration);

		// initialize emailBean
		InterviewViewDto inter = new InterviewViewDto();
		inter.setStartTime(test.getStartTime().toString());
		inter.setDate(test.getDate().toString());
		inter.setRoom(test.getRoom());
		inter.setEndTime(test.getEndTime().toString());
		CandidateDTO candidate = new CandidateDTO();
		TemplateViewDto template = new TemplateViewDto();
		template.setId(test.getTemplate().getId());
		template.setTitle(test.getTemplate().getTitle());
		inter.setTemplate(template);
		candidate.setFirstName(test.getCandidate().getFirstName());
		candidate.setLastName(test.getCandidate().getLastName());
		candidate.setEmail(test.getCandidate().getEmail());
		inter.setCandidate(candidate);
		emailBean.setTemplateId(test.getTemplate().getId());
		emailBean.setEmail(test.getCandidate().getEmail());
		emailBean.setInterviewDto(inter);

		emailBean.setEmployeeId(employeeId);
		emailBean.setIdto(idto);
		emailBean.setSelectedRoomID(test.getRoom().getId());
		emailBean.setSelectedTemplateID(test.getTemplate().getId());
		emailBean.setIdCandidate(test.getCandidate().getId());
		emailBean.setDelete(false);
		// redirect to emailCandidateContent page
		if (errorMessage.equals("Interview Succesfully edited!"))
			try {
				reschedule = false;
				FacesContext.getCurrentInstance().getExternalContext().redirect(
						"/MSGCandidateTesting/faces/testerhome.xhtml");
			} catch (IOException e) {
				e.printStackTrace();
			}
	}

	public int computeDuration(InterviewDTO test) {

		String[] tokens1 = test.getStartTime().toString().split(":");
		String[] tokens2 = test.getEndTime().toString().split(":");

		int hours = Integer.parseInt(tokens2[0]) - Integer.parseInt(tokens1[0]);
		int minutes = Integer.parseInt(tokens2[1]) - Integer.parseInt(tokens1[1]) + hours * 60;

		return minutes;
	}

	/**
	 * @param details
	 *            the details to set
	 */
	public void setDetails(String details) {
		this.details = details;
	}

	/**
	 * @return the details
	 */
	public String getDetails() {
		return details;
	}

	/**
	 * @param selectedTemplateID
	 *            the selectedTemplateID to set
	 */
	public void setSelectedTemplateID(int selectedTemplateID) {
		this.selectedTemplateID = selectedTemplateID;
	}

	/**
	 * @return the selectedTemplateID
	 */
	public int getSelectedTemplateID() {
		return selectedTemplateID;
	}

	/**
	 * @param templateDTOs
	 *            the templateDTOs to set
	 */
	public void setTemplateDTOs(List<TemplateDTO> templateDTOs) {
		this.templateDTOs = templateDTOs;
	}

	/**
	 * @return the templateDTOs
	 */
	public List<TemplateDTO> getTemplateDTOs() {
		templateDTOs.clear();
		templateDTOs = templateDAO.findAllTemplates();
		return templateDTOs;
	}

	/**
	 * @param selectedTemplate
	 *            the selectedTemplate to set
	 */
	public void setSelectedTemplate(TemplateDTO selectedTemplate) {
		this.selectedTemplate = selectedTemplate;
	}

	public TemplateDTO getSelectedTemplate() {
		return selectedTemplate;
	}

	/**
	 * @param templateCategoryDTOs
	 *            the templateCategoryDTOs to set
	 */
	public void setTemplateCategoryDTOs(List<TemplateCategoryDTO> templateCategoryDTOs) {
		this.templateCategoryDTOs = templateCategoryDTOs;
	}

	/**
	 * @return the templateCategoryDTOs
	 */
	public List<TemplateCategoryDTO> getTemplateCategoryDTOs() {
		templateCategoryDTOs.clear();
		templateCategoryDTOs = templateCategoryDAO.getTemplateCategoryListByTemplate(selectedTemplate);
		return templateCategoryDTOs;
	}

	public void setRooms(List<String> rooms) {
		this.rooms = rooms;
	}

	public List<String> getRooms() {
		return rooms;
	}

	public void setSelectedRoom(RoomDTO selectedRoom) {
		this.selectedRoom = selectedRoom;
	}

	public RoomDTO getSelectedRoom() {
		return selectedRoom;
	}

	public void setTotalRooms(int totalRooms) {
		this.totalRooms = totalRooms;
	}

	public int getTotalRooms() {
		totalRooms = roomDAO.getRoomByAddress(selectedRoom.getAddress()).getNumberOfStations();
		return totalRooms;
	}

	public void setSchedule(List<Integer> schedule) {
		this.schedule = schedule;
	}

	public List<Integer> getSchedule() {
		return schedule;
	}

	public void setSelectedRoomID(int selectedRoomID) {
		this.selectedRoomID = selectedRoomID;
	}

	public List<String> getWeekDate() {
		return weekDate;
	}

	public Calendar getSelectedEndDate() {
		return selectedEndDate;
	}

	public void setSelectedEndDate(Calendar selectedEndDate) {
		this.selectedEndDate = selectedEndDate;
	}

	public void setWeekDate(List<String> weekDate) {
		this.weekDate = weekDate;
	}

	/**
	 * @return the interviewView
	 */
	public InterviewViewDto getInterviewView() {
		return interviewView;
	}

	/**
	 * @param interviewView
	 *            the interviewView to set
	 */
	public void setInterviewView(InterviewViewDto interviewView) {
		this.interviewView = interviewView;
	}

	public List<String> getWeekDays() {
		return weekDays;
	}

	public void setWeekDays(List<String> weekDays) {
		this.weekDays = weekDays;
	}

	public List<Calendar> getWeek() {
		return week;
	}

	public void setWeek(List<Calendar> week) {
		this.week = week;
	}

	public String getSelDate() {
		return selDate;
	}

	public void setSelDate(String selDate) {
		this.selDate = selDate;
	}

	public Calendar getSelectedDate() {
		return selectedDate;
	}

	public void setSelectedDate(Calendar selectedDate) {
		this.selectedDate = selectedDate;
	}

	public int getSelectedRoomID() {
		return selectedRoomID;
	}

	public List<RoomDTO> getRoomDTOs() {
		roomDTOs.clear();
		roomDTOs = roomDAO.getAllRooms();
		return roomDTOs;
	}

	public void setRoomDTOs(List<RoomDTO> roomDTOs) {
		this.roomDTOs = roomDTOs;
	}

	public List<Integer> getHours() {
		return hours;
	}

	public void setHours(List<Integer> hours) {
		this.hours = hours;
	}

	public int getSelectedStartHour() {
		return selectedStartHour;
	}

	public void setSelectedStartHour(int selectedStartHour) {
		this.selectedStartHour = selectedStartHour;
	}

	public int getSelectedStartMinute() {
		return selectedStartMinute;
	}

	public void setSelectedStartMinute(int selectedStartMinute) {
		this.selectedStartMinute = selectedStartMinute;
	}

	public int getSelectedEndHour() {
		return selectedEndHour;
	}

	public void setSelectedEndHour(int selectedEndHour) {
		this.selectedEndHour = selectedEndHour;
	}

	public int getSelectedEndMinute() {
		return selectedEndMinute;
	}

	public void setSelectedEndMinute(int selectedEndMinute) {
		this.selectedEndMinute = selectedEndMinute;
	}

	public List<Integer> getMinutes() {
		return minutes;
	}

	public void setMinutes(List<Integer> minutes) {
		this.minutes = minutes;
	}

	public List<Integer> getEndHours() {
		return endHours;
	}

	public void setEndHours(List<Integer> endHours) {
		this.endHours = endHours;
	}

	public List<Integer> getEndMinutes() {
		return endMinutes;
	}

	public void setEndMinutes(List<Integer> endMinutes) {
		this.endMinutes = endMinutes;
	}

	public void setErrorMessage(String errorMessage) {
		this.errorMessage = errorMessage;
	}

	public String getErrorMessage() {
		return errorMessage;
	}

	public void setEmployeeId(int employeeId) {
		this.employeeId = employeeId;
	}

	public int getEmployeeId() {
		return employeeId;
	}

	public void setCandidate(CandidateViewDto candidate) {
		this.candidate = candidate;
	}

	public CandidateViewDto getCandidate() {
		return candidate;
	}

	public void setIdto(InterviewDTO idto) {
		this.idto = idto;
	}

	public InterviewDTO getIdto() {
		return idto;
	}

	public void setNextButton(String nextButton) {
		this.nextButton = nextButton;
	}

	public String getNextButton() {
		return nextButton;
	}

	public void setCurrentWeek(String currentWeek) {
		this.currentWeek = currentWeek;
	}

	public String getCurrentWeek() {
		return currentWeek;
	}

	public void setColor(String color) {
		this.color = color;
	}

	public String getColor() {
		return color;
	}

	public void setReschedule(Boolean reschedule) {
		this.reschedule = reschedule;
	}

	public Boolean getReschedule() {
		return reschedule;
	}

	public List<String> getColorList() {
		return colorList;
	}

	public void setColorList(List<String> colorList) {
		this.colorList = colorList;
	}

	public EmailBean getEmailBean() {
		return emailBean;
	}

	public void setEmailBean(EmailBean emailBean) {
		this.emailBean = emailBean;
	}

	/**
	 * @param messageClass
	 *            the messageClass to set
	 */
	public void setMessageClass(String messageClass) {
		this.messageClass = messageClass;
	}

	/**
	 * @return the messageClass
	 */
	public String getMessageClass() {
		return messageClass;
	}

}
